<template>
  <p-card :bordered="false" class="peopleInfo">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <p-form layout="inline" @keyup.enter.native="searchQuery">
        <p-row :gutter="24">
          <p-col :xl="6" :lg="7" :md="8" :sm="24" v-for="(item, index) in queryParamArr" :key="index">
            <p-form-item :label="item.label">
              <p-input :placeholder="item.placeholder" v-model="item.value"></p-input>
            </p-form-item>
          </p-col>
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <p-button type="primary" @click="searchQuery" icon="search">查询</p-button>
              <p-button
                type="primary"
                @click="searchReset"
                icon="reload"
                style="margin-left: 8px"
              >重置</p-button>
            </span>
          </p-col>
        </p-row>
      </p-form>
    </div>


    <div>

      <p-button type="primary" @click="showRootModal">新增班组</p-button>
      <p-button type="primary" @click="showSubModal">新增子班组</p-button>


    </div>


    <!-- table区域-begin -->
    <div class="peopleInfo-table">
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>

        <span style="float:right;">
          <a @click="handleExportXls('关键字段信息')">
            <p-icon type="download" />导出
          </a>
          <p-divider type="vertical" />
          <p-upload
            name="file"
            :showUploadList="false"
            :multiple="false"
            :headers="tokenHeader"
            :action="importExcelUrl"
            @change="handleImportExcel"
          >
            <a>
              <p-icon type="import" />导入
            </a>
          </p-upload>
          <p-divider type="vertical" />
          <a @click="loadData()">
            <p-icon type="sync" />刷新
          </a>
          <p-divider type="vertical" />
          <p-popover title="自定义列" trigger="click" placement="leftBottom" :overlay-style="getWidth">
            <template slot="content">
              <p-checkbox-group
                @change="onColSettingsChange"
                v-model="settingColumns"
                :defaultValue="settingColumns"
              >
                <p-row>
                  <template v-for="(item, index) in defColumns">
                    <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                      <p-col :span="12">
                        <p-checkbox :value="item.dataIndex">{{ item.title }}</p-checkbox>
                      </p-col>
                    </template>
                  </template>
                </p-row>
              </p-checkbox-group>
            </template>
            <a>
              <p-icon type="setting" />自定义列
            </a>
          </p-popover>
        </span>
      </div>

     <p-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :scroll="tableScroll"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @expand="handleExpand"
        @change="handleTableChange"
      >

        <template slot="status" slot-scope="text, record">
          <p-switch size="small"  v-model="record.status" @change="onSwitchChange(record)" />       
        </template>        

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <p-divider type="vertical" />
          <p-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </p-popconfirm>          
        </span>
      </p-table>      

    </div>

    <!-- 新增班组 -->
    <ClassInfoRootModal ref = 'classInfoRootModal' @handleSuccess='loadData'></ClassInfoRootModal>
    <!-- 新增子班组 -->
    <ClassInfoSubModal ref = 'classInfoSubModal'  @handleSuccess='loadData'></ClassInfoSubModal>
    
  </p-card>
</template>

<script type="text/javascript">
import JSuperQuery from "@/components/jeecg/JSuperQuery.vue";
import { postAction, getAction, deleteAction } from "@/api/manage";
import { filterObj } from "@/utils/util";
import ClassInfoRootModal from './modules/classInfoRootModal.vue';
import ClassInfoSubModal from './modules/classInfoSubModal.vue';
import { timestampToDatetime } from "@/utils/util";


export default { 
  data() {
    return {
      queryParamArr: [
        {
          label: "班组编码",
          placeholder: "请输入班组编码",
          type: 'input',
          key: 'classno',
          value: ''
        },
        {
          label: "班组名称",
          placeholder: "请输入班组名称",
          type: 'input',
          key: 'classname',
          value: ''
        }
      ],
      defColumns: [
        {
          title: "班组编码",
          align: "center",
          dataIndex: "classno",
        },
        {
          title: "班组名称",
          align: "center",
          dataIndex: "classname",
        },
        {
          title: "班组描述",
          align: "center",
          dataIndex: "classdescription",
        },
        {
          title: "创建时间",
          align: "center",
          dataIndex: "createTime",
          customRender: function (text) {
            return timestampToDatetime(text);
          },          
        },
        {
          title: "创建人",
          align: "center",
          dataIndex: "createBy",
        },
        {
          title: "状态",
          align: "center",
          dataIndex: "status",
          scopedSlots: { customRender: "status" },
        },
        
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          scopedSlots: { customRender: "action" },
        },
      ],
      url: {
        list: '/mes-manpower/mesHrClassInfo/list',  // 分页获取班组信息列表
        childList: '/mes-manpower/mesHrClassInfo/childList', // 获取子节点
        delete: '/mes-manpower/mesHrClassInfo', // 删除
        editStatus: '/mes-manpower/mesHrClassInfo/status' // 修改状态
      },      
      test: {
        a: 1,
        b: 34
      },
      queryParam: {},
      originQueryParam: {},
      loading: false,
      selectedRowKeys: [],
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading: false,
      /* table选中keys */
      selectedRowKeys: [],
      /* table选中records */
      selectionRows: [],
      /* 查询折叠 */
      toggleSearchStatus: false,
      /* 高级查询条件生效状态 */
      superQueryFlag: false,
      /* 高级查询条件 */
      superQueryParams: '',      
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ["10", "20", "50"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },      
      dataSource: [],
      // 表头
      columns: [],
      //列设置
      settingColumns: [],
   
    };
  },
  computed: {
    tableScroll () {
      if (this.columns.length > 13) {
        return { x: this.columns.length * 150 - 450 };
      }
    },
  },

  watch: {
    queryParamArr: {
      handler(newName, oldName) {
        newName.forEach( ele => {
          this.$set(this.queryParam, ele.key, ele.value)
          console.log('this.queryParam', this.queryParam);
        } )        
      },
      deep: true,
      immediate: true
    }
  },  

  mounted() {
    this.originQueryParam = JSON.parse(JSON.stringify(this.queryParam))

    this.initColumns()
    this.setDefColumns();
    this.loadData(1)
  },
  methods: {

    // 初始化 tabe的Columns
    initColumns() {
      let allSettingColumns = [];
      console.log('this.defColumns', this.defColumns);
      
      this.defColumns.forEach(function (item, i, array) {
        allSettingColumns.push(item.dataIndex);
      });
      this.settingColumns = allSettingColumns;
      this.columns = this.defColumns;     
    },

    //列设置更改事件
    onColSettingsChange(checkedValues) {
      console.log(323);
      console.log(checkedValues);
      
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter((item) => {
        if (item.key == "rowIndex" || item.dataIndex == "action") {
          return true;
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true;
        }
        return false;
      });
      this.columns = cols;
    },

    // 新增根节点
    showRootModal(){
      this.$refs.classInfoRootModal.showModal()
    },
    // 显示子班组弹窗
    showSubModal(){
      this.$refs.classInfoSubModal.showModal()
    },

    // table 的分页事件
    handleTableChange(pagination, filters, sorter) {
      console.log(pagination);
      console.log(filters);
      console.log(sorter);
      
      // 分页、排序、筛选变化时触发
      // TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
      }        
       //筛选 多选
       Object.keys(filters).map((key) => {
        let k = key
        let data = []
        filters[k].forEach((item,index)=>{
          data.push(item)
        })
          //表头筛选表头带的value值是字典的value，接口筛选的时候需要的是字典的key 这边把表头携带的_deicText  默认去掉
        if(k.indexOf("_dictText") > -1) {
          k = k.replace("_dictText","")
        }
        this.queryParam[k] = data.toString("")
      })     
      this.ipagination = pagination
      this.loadData()
    },
    // 设置table的 columns
    setDefColumns() {
      if (this.columns.length > 13) {
        let arrLength = this.columns.length - 1;
        this.columns.forEach((item, index) => {
          item["width"] = 130;
        });
        this.columns[arrLength]["fixed"] = "right";
        this.columns[0]["fixed"] = "left";
        this.columns[1]["fixed"] = "left";
      }
    },    
    // 查询
    searchQuery() {
      this.loadData(1)
    },
    // 重置查询
    searchReset() {
      this.queryParam = this.originQueryParam
      this.loadData(1)
    },

    // 获取查询条件
    getQueryParams() {
      let sqp = {};
      if (this.superQueryParams) {
        sqp["superQueryParams"] = encodeURI(this.superQueryParams);
      }
      var param = Object.assign(sqp, this.queryParam);
      param.pageNo = this.ipagination.current;
      param.limit = this.ipagination.pageSize;
      return filterObj(param);
    },    
    // table选中改变
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },    
    // 清除table选中
    onClearSelected() {
      this.selectedRowKeys = [];
    },
    // 查询列表
    loadData(pageIndex){
      if (pageIndex === 1) {
        this.ipagination.pageIndex = 1;
      }      
      this.onClearSelected();
      const params = this.getQueryParams(); //查询条件
      params.parentId = '-1'
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = this.getDataByResult(res.data.records);
          this.ipagination.total = res.data.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
        this.loading = false;
      });      
    },    


    // 对字节点处理
    getDataByResult (result) {
      return result.map(item => {
        //判断是否标记了带有子节点
        if (item.hasChild == 1) {
          let loadChild = {
            id: item.id + "_loadChild",
            name: "loading...",
            isLoading: true
          };
          item.children = [loadChild];
        }
        return item;
      });
    },    

    // 展开子节点
    handleExpand(expanded, record){
      const params = {
        parentId: record.id
      }
      getAction(this.url.childList,params).then((res)=>{
      if(res.success){
        if(res.data && res.data.length>0){
          record.children = this.getDataByResult(res.data)
          this.dataSource = [...this.dataSource]
        }else{
          record.children=''
          record.hasChildrenField= false
        }
      }else{
        this.$message.warning(res.msg)
      }
    })

    },

  // 修改状态
  onSwitchChange(record){
    console.log(record);
    const params = {
      status: record.status ? 1 : 0,
      id: record.id,
    }
    postAction(this.url.editStatus, params).then( res => {
      if (res.success) {
        this.$message.success("修改状态成功!")
      } else {
        this.$message.error("修改状态失败!")
        record.status = !record.status
      }
    } )
  },

    // 删除班组
    handleDelete(id) {
      deleteAction(`${this.url.delete}/${id}`).then(res => {
        if(res.success) {
          this.loadData()
          this.$message.success('删除成功')
        } else {
          this.$message.error('删除失败')
        }
      })
    },

    // 编辑
    handleEdit(record) {
      if(record.parentId == '-1') {
        this.$refs.classInfoRootModal.showModal(record)
      }else {
        this.$refs.classInfoSubModal.showModal(record)
      }
    },



  },    

  components: {
    JSuperQuery,
    ClassInfoRootModal,
    ClassInfoSubModal
  },
};
</script>

<style lang="less" scoped>
</style>
